var express = require('express');
var router = express.Router();
const response = require('../utils/response');
const svgCaptcha = require('svg-captcha');

/**
 * @description 生成4位随机验证码图片
 * @route GET /common/captcha
 */
router.get('/captcha', async (req, res) => {
  try {
    // 生成svg验证码
    const captcha = svgCaptcha.create({
      size: 4, // 验证码长度
      noise: 2, // 干扰线条数
      color: true, // 验证码字符将有不同的颜色
      background: '#f0f0f0', // 背景颜色
      width: 120,
      height: 40
    });
    // 将SVG转换为Base64格式
    const base64Image = Buffer.from(captcha.data).toString('base64');
    res.json(response(true, '验证码生成成功', {
      image: `data:image/svg+xml;base64,${base64Image}`,
      code: captcha.text
    }));
  } catch (error) {
    res.status(500).json(response(false, error.message, null, 500));
  }
});

module.exports = router;

